package com.runen.infinitemovement.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.amap.api.location.AMapLocation;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.CompanyAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.PictrueEntity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.LocationUtil;
import com.runen.infinitemovement.tool.UiUtil;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.CompanySizePoppupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.PermissionUtils;
import com.runen.rxnetlibrary.utils.StringUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.runen.rxnetlibrary.utils.constant.PermissionConstants;
import com.runen.rxnetlibrary.utils.helper.DialogHelper;
import com.zhihu.matisse.Matisse;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CreateLevel1OrganizationsActivity extends BaseActivity {
    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.ll_logo)
    LinearLayout ll_logo;
    @BindView(R.id.rci_logo)
    RoundedCornersImage rci_logo;
    @BindView(R.id.edt_corps_nam)
    EditText edtCorpsNam;
    @BindView(R.id.tv_company_member_num)
    TextView tvCompanyMemberNum;
    @BindView(R.id.edt_name)
    EditText edtName;
    @BindView(R.id.edt_post)
    EditText edtPost;
    @BindView(R.id.edt_company_phone)
    EditText edtCompanyPhone;
    @BindView(R.id.edt_company_password)
    EditText edt_company_password;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    private List<Uri> avatar = new ArrayList<>();
    private int REQUEST_CODE_CHOOSE = 23;

    private LocationManager locationManager;

    @Nullable
    @Override
    protected int getLayoutId() {
        return R.layout.activity_create_level1_organizations;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        topTitle.setText("新增一级组织");
    }

    @SuppressLint("WrongConstant")
    private void onPermissions() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //判断是否开启了GPS
        boolean ok = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (ok) {
            //请求动态权限
            PermissionUtils.permission(PermissionConstants.LOCATION,
                    PermissionConstants.ACCESS_FINE_LOCATION,
                    PermissionConstants.WRITE_EXTERNAL_STORAGE,
                    PermissionConstants.ACCESS_COARSE_LOCATION)
                    .rationale(new PermissionUtils.OnRationaleListener() {
                        @Override
                        public void rationale(final ShouldRequest shouldRequest) {
                            DialogHelper.showRationaleDialog(shouldRequest);
                        }
                    })
                    .callback(new PermissionUtils.FullCallback() {
                        @Override
                        public void onGranted(List<String> permissionsGranted) {
                            showDialog();
                            LocationUtil.getInstance().initOption(CreateLevel1OrganizationsActivity.this, true);
                            LocationUtil.getInstance().startLocation();
                            LocationUtil.getInstance().setLocationListener(new LocationUtil.GetLocationSuccseeListener() {
                                @Override
                                public void getLocation(AMapLocation latLng) {
                                    JSONObject object = new JSONObject();
                                    try {
                                        object.put("logo", logo);
                                        object.put("location", latLng.getLongitude() + "," + latLng.getLatitude());
                                        object.put("teamName", companyName);
                                        object.put("companyContactsName", name);
                                        if (companySize.contains("60人以下")) {
                                            object.put("companyScaleType", 1);
                                        } else if (companySize.contains("60-100人")) {
                                            object.put("companyScaleType", 2);
                                        } else if (companySize.contains("100-300人")) {
                                            object.put("companyScaleType", 3);
                                        }
                                        object.put("companyPositionName", post);
                                        object.put("companyMobile", phone);
                                        object.put("password", edt_company_password.getText().toString());
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }

                                    new CompanyAPI().addCorps(object.toString(), new BaseResultCallback<BaseResponseEntity<String>>() {
                                        @Override
                                        public void onResponse(BaseResponseEntity<String> response) {
                                            dismissDialog();
                                            if (response.getCode() == 0) {
                                                if (!TextUtils.isEmpty(response.getData())) {
                                                    Intent intent = new Intent(CreateLevel1OrganizationsActivity.this, CheckTeamActivity.class);
                                                    intent.putExtra(ActivityCompat.TEAM_GROUP_ID, response.getData());
                                                    startActivity(intent);
                                                }
                                                finish();
                                            }
                                        }

                                        @Override
                                        public void onError(Throwable e, String body) {
                                            super.onError(e, body);
                                            dismissDialog();
                                        }
                                    });
                                }

                                @Override
                                public void locationFail() {

                                }
                            });
                        }

                        @Override
                        public void onDenied(List<String> permissionsDeniedForever,
                                             List<String> permissionsDenied) {
                            if (!permissionsDeniedForever.isEmpty()) {
                                DialogHelper.showOpenAppSettingDialog();
                            }
                        }
                    })
                    .request();
        } else {
            //若未开启，弹框让用户选择去开
            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle("获取位置失败")
                    .setMessage("未开启位置信息，前往开启")
                    .setCancelable(false)
//                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//
//                        }
//                    })
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 1);
                        }
                    })
                    .show();
        }

    }

    @OnClick({R.id.top_btn_left, R.id.ll_logo, R.id.tv_company_member_num, R.id.tv_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.ll_logo:
                onPermission();
                break;
            case R.id.tv_company_member_num:
                showPopup();
                break;
            case R.id.tv_sure:
                onSubmit();
                break;
        }
    }

    private String companyName;
    private String name, post, phone;

    private void onSubmit() {
        companyName = edtCorpsNam.getText().toString();
        name = edtName.getText().toString();
        post = edtPost.getText().toString();
        phone = edtCompanyPhone.getText().toString();
        if (TextUtils.isEmpty(logo)) {
            ToastUtils.showShort("请上传企业LOGO");
            return;
        }
        if (TextUtils.isEmpty(companyName)) {
            ToastUtils.showShort("请输入军团名称");
            return;
        }
        if (TextUtils.isEmpty(companySize)) {
            ToastUtils.showShort("请选择企业规模");
            return;
        }
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showShort("请输入姓名");
            return;
        }
        if (TextUtils.isEmpty(post)) {
            ToastUtils.showShort("请输入职位");
            return;
        }
        if (!StringUtil.isMobileNo(phone)) {
            ToastUtils.showShort("请输入正确的联系方式");
            return;
        }
        onPermissions();


    }

    private CompanySizePoppupWindow sizePoppupWindow;
    private String companySize;
    private String logo;

    private void showPopup() {
        sizePoppupWindow = CompanySizePoppupWindow.getInstance(this);
        sizePoppupWindow.show();
        sizePoppupWindow.setOnHozonClickListener(new CompanySizePoppupWindow.OnHozonClickListener() {
            @Override
            public void onHozomClick(String corpsName) {
                tvCompanyMemberNum.setText(corpsName);
                companySize = corpsName;
                sizePoppupWindow.dismiss();
            }
        });
    }


    /**
     * 获取拍照权限
     */
    private void requestCamera() {
        UiUtil.getImageSelectorConfig(this, REQUEST_CODE_CHOOSE);
    }

    @SuppressLint("WrongConstant")
    private void onPermission() {
        //请求动态权限
        PermissionUtils.permission(
                PermissionConstants.STORAGE,
                PermissionConstants.CAMERA,
                PermissionConstants.WRITE_EXTERNAL_STORAGE,
                PermissionConstants.ACCESS_COARSE_LOCATION)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(final ShouldRequest shouldRequest) {
                        DialogHelper.showRationaleDialog(shouldRequest);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(List<String> permissionsGranted) {
                        requestCamera();
                    }

                    @Override
                    public void onDenied(List<String> permissionsDeniedForever,
                                         List<String> permissionsDenied) {
                        if (!permissionsDeniedForever.isEmpty()) {
                            DialogHelper.showOpenAppSettingDialog();
                        }
                    }
                })
                .request();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            if (data != null) {
                avatar = Matisse.obtainResult(data);
                if (avatar != null && avatar.size() > 0) {
                    Log.e("OnActivityResult ", String.valueOf(avatar.get(0)));
                    GlideUtils.loadImage(this, avatar.get(0).toString(), rci_logo);
                    File file = null;
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                        file = CommonUtil.uriToFileApiQ(this, avatar.get(0));
                    } else {
                        file = CommonUtil.uri2File(this, avatar.get(0));
                    }
                    updateByImgUrl(file);
                }
            }
        }
    }

    private void updateByImgUrl(File imaUrl) {
        Log.e("OnActivityResult2 ", imaUrl.toString());
        TreeMap<String, String> mapType = new TreeMap<>();
        mapType.put("type", "headImg");
//        File file = ScreenShotHelper.compressImage2(CommonUtil.getImage(imaUrl.getPath()), this);
        TreeMap<String, File> mapFile = new TreeMap<>();
        mapFile.put("file", imaUrl);
        new UserAPI().putFile(mapType, mapFile, new BaseResultCallback<PictrueEntity>() {
            @Override
            public void onResponse(PictrueEntity response) {
                if (response.code == 0) {
                    if (response.data != null) {
                        Message message = new Message();
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("headImgUrl", response.data.url);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String headUrl = bundle.getString("headImgUrl");
                    logo = headUrl;
                    break;
            }
        }
    };

}